package com.yjf.ljr.activity;

import com.yjf.ljr.R;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.dataclass.AcountManageDataClass;
import com.yjf.ljr.dataclass.AcountManageDataClass.AcountManageDataInfo;
import com.yjf.ljr.dataclass.ChecktransferMoneyDataClass;
import com.yjf.ljr.dataclass.PreTransferDataClass;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ApplicationTransferActivity extends IjActivity implements OnClickListener {
	@ID("btApplicationTransfer")
	private Button mBtApplicationTransfer;
	private String tradeId;// 项目查询Id
	private String tradeDetailId;// 转让详情查询Id
	@ID("tvCanTransloanName")
	private TextView mTvCanTransloanName;// 项目名
	@ID("tvCanTransRemainder")
	private TextView mTvCanTransRemainder;// 剩余本金
	@ID("tvCanTransInterest")
	private TextView mTvCanTransInterest;// 持有期待收利息
	@ID("tvCanTransTotalMoney")
	private TextView mTvCanTransTotalMoney;// 合计
	@ID("tvCanTransDownToUp")
	private TextView mTvCanTransDownToUp;// 转让价格区间
	@ID("tvCanTransbuyerDebtProfitRate")
	private TextView mTvCanTransbuyerDebtProfitRate;// 预期年化利率：
	@ID("tvCanTransfee")
	private TextView mTvCanTransfee;// 转让手续费：
	@ID("tvCanTransdeadline")
	private TextView mTvCanTransdeadline;// 转让截止日期：
	@ID("ettransferPrice")
	private EditText mEttransferPrice;// 转让价格
	private String investAmount;// 投资金额

	private String yjfPaypassUrl;
	private boolean applicationBtnCli = false;// 条件不满足，不允许点击 确定申请按钮
	private String messageButCli = "";// 条件不满足，不允许点击 确定申请按钮的提示信息
	@ID("btReturnNoChange")
	private Button mBtbtReturnNoChange;// 暂不修改

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_application_transfer);
		initControl();
	}

	/***** 监听输入隔一秒发一次请求 *******/
	private Handler inputHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				if (!TextUtils.isEmpty(mEttransferPrice.getText().toString().trim())) {
					new ChecktransferMoneyTask(mEttransferPrice.getText().toString().trim(), tradeDetailId).execute();
				}
				break;

			default:
				break;
			}
		};

	};

	private void initControl() {
		setTitleStr("申请转让");
		setLeftBtnClick();
		mBtbtReturnNoChange.setOnClickListener(this);// 暂不修改
		tradeId = getIntent().getStringExtra("tradeId");
		tradeDetailId = getIntent().getStringExtra("tradeDetailId");
		investAmount = getIntent().getStringExtra("investAmount");
		mBtApplicationTransfer.setOnClickListener(this);
		applicationBtnCli = false;
		if (TextUtils.isEmpty(mEttransferPrice.getText().toString())) {
			messageButCli = "请输入转让金额";
		}
		showProgressDialog();
		new PreTransferTask(tradeId, tradeDetailId).execute();
		mEttransferPrice.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				inputHandler.removeMessages(0);
				inputHandler.sendEmptyMessageDelayed(0, 1 * 1000);

			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btApplicationTransfer:
			if (applicationBtnCli) {
				new AcountManageTask().execute();
//				Intent intent = new Intent(mContext, ConfirmationTransferActivity.class);
//				intent.putExtra("transferPrice", mEttransferPrice.getText().toString().trim());
//				intent.putExtra("CanTransfee", mTvCanTransfee.getText().toString().trim());
//				intent.putExtra("CanTransbuyerDebtProfitRate", mTvCanTransbuyerDebtProfitRate.getText().toString()
//						.trim());
//				intent.putExtra("CanTransdeadline", mTvCanTransdeadline.getText().toString().trim());
//				intent.putExtra("tradeDetailId", tradeDetailId);
//				intent.putExtra("yjfPaypassUrl", yjfPaypassUrl);
//				startActivityForResult(intent, CommonData.CONFIRMATION_TRANSFER);
			} else {
				showToast(messageButCli);
			}

			break;
		case R.id.btReturnNoChange:
			// 暂不修改
			finish();
			break;

		default:
			break;
		}
	}

	/***** 获取前置信息 *******/
	private class PreTransferTask extends AsyncTask<Void, Void, String> {
		PreTransferDataClass dc = new PreTransferDataClass();
		RequestObject mObject = new RequestObject();
		private String tradeId;// 项目查询Id
		private String tradeDetailId;// 转让详情查询Id

		public PreTransferTask(String tradeId, String tradeDetailId) {
			this.tradeDetailId = tradeDetailId;
			this.tradeId = tradeId;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			mObject.method = "preTransfer";
			mObject.map.put("tradeId", tradeId);
			mObject.map.put("tradeDetailId", tradeDetailId);
			return requestDataAndGetErrorMsg(mObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (TextUtils.isEmpty(result)) {
				mTvCanTransloanName.setText(dc.result.loanName);// 项目名称
				mTvCanTransDownToUp.setText(dc.result.downMoney + "~" + dc.result.upMoney);
				double receivePrincipalMoneyd = 0;// 剩余本金
				double receivableMoney = 0;// 持有期利息
				if (TextUtils.isEmpty(dc.result.receivePrincipalMoney)) {
					mTvCanTransRemainder.setText("无");// 剩余本金
				} else {
					receivePrincipalMoneyd = Double.parseDouble(dc.result.receivePrincipalMoney.replace(",", ""));
					mTvCanTransRemainder.setText("￥" + dc.result.receivePrincipalMoney);// 剩余本金
				}
				if (TextUtils.isEmpty(dc.result.receivableMoney)) {
					mTvCanTransInterest.setText("无");// 持有期利息
				} else {
					receivableMoney = Double.parseDouble(dc.result.receivableMoney.replace(",", ""));
					mTvCanTransInterest.setText("￥" + dc.result.receivableMoney);// 持有期利息
				}
				mTvCanTransTotalMoney.setText("￥" + (receivePrincipalMoneyd + receivableMoney));

				if (!TextUtils.isEmpty(dc.result.deadline) && dc.result.deadline.length() > 10) {
					mTvCanTransdeadline.setText(dc.result.deadline.substring(0, 10));
				} else {
					mTvCanTransdeadline.setText(dc.result.deadline);
				}
				yjfPaypassUrl = dc.result.yjfPaypassUrl;
			} else {
				showToast(result);
				applicationBtnCli = false;
				messageButCli = dc.msg;
			}
			dismissProgressDialog();
		}
	}

	private class ChecktransferMoneyTask extends AsyncTask<Void, Void, String> {
		RequestObject mObject = new RequestObject();
		private String amount;// 转让金额
		private String tradeDetailId;// 转让详情查询Id
		ChecktransferMoneyDataClass dc = new ChecktransferMoneyDataClass();

		public ChecktransferMoneyTask(String amount, String tradeDetailId) {
			// TODO Auto-generated constructor stub
			this.amount = amount;
			this.tradeDetailId = tradeDetailId;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			mObject.method = "checktransferMoney";
			mObject.map.put("amount", amount);
			mObject.map.put("tradeDetailId", tradeDetailId);
			return requestDataAndGetErrorMsg(mObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if ("-1".equals(dc.code)) {
				loginWebview();
				return;
			}
			if (TextUtils.isEmpty(result)) {
				mTvCanTransbuyerDebtProfitRate.setText(dc.buyerDebtProfitRate);
				mTvCanTransfee.setText(dc.fee);
				applicationBtnCli = true;
			} else {
				showToast(result);
				applicationBtnCli = false;
				messageButCli = dc.msg;
			}
			dismissProgressDialog();
		}
	}

	/********* onActivityResult ********/
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, intent);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case CommonData.REQUEST_CODE_LOGIN:
				showProgressDialog();
				new PreTransferTask(tradeId, tradeDetailId).execute();
				break;
			case CommonData.CONFIRMATION_TRANSFER:
				// 够买成功返回
				setResult(RESULT_OK);
				ApplicationTransferActivity.this.finish();
				break;
			default:
				break;
			}
		}
	}
	
	class AcountManageTask extends AsyncTask<Void, Void, String> {
		private AcountManageDataClass dc = new AcountManageDataClass();

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showProgressDialog();
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			RequestObject mObject = new RequestObject();
			mObject.method = "appAccountInfo";
			return requestDataAndGetErrorMsg(mObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			dismissProgressDialog();
			if ("-1".equals(dc.code)) {
				loginWebview();
				return;
			}
			if (!TextUtils.isEmpty(result)) {
				showToast(result);
			} else {
				AcountManageDataInfo data = dc.accountInfo;
				String openStatus1 = getString(R.string.payment_status_on);
				String openStatus2 = getString(R.string.payment_status_active);
				final String mobile = data.mobile;
				if (TextUtils.isEmpty(data.openState)
						|| (!data.openState.equals(openStatus1) && !data.openState.equals(openStatus2))) {
					dismissProgressDialog();
					AlertDialog.Builder builder = new AlertDialog.Builder(ApplicationTransferActivity.this);
					builder.setTitle("提示");
					builder.setMessage("您的账户未激活，激活支付账户后方可充值、投资。");
					if(!TextUtils.isEmpty(mobile)) {
						builder.setPositiveButton("立即激活", new DialogInterface.OnClickListener(){

							@Override
							public void onClick(DialogInterface dialog, int which) {
								Intent intent = new Intent(ApplicationTransferActivity.this,RegistrationActiveActivity.class);
								intent.putExtra("phoneNum", mobile);
								startActivity(intent);
							}
							
						});
						builder.setNegativeButton("暂不激活", null);
					} else {
						builder.setPositiveButton("确定", null);
					}
					AlertDialog dialog = builder.create();					
					dialog.show();
					return;
				}

				Intent intent = new Intent(mContext, ConfirmationTransferActivity.class);
				intent.putExtra("transferPrice", mEttransferPrice.getText().toString().trim());
				intent.putExtra("CanTransfee", mTvCanTransfee.getText().toString().trim());
				intent.putExtra("CanTransbuyerDebtProfitRate", mTvCanTransbuyerDebtProfitRate.getText().toString()
						.trim());
				intent.putExtra("CanTransdeadline", mTvCanTransdeadline.getText().toString().trim());
				intent.putExtra("tradeDetailId", tradeDetailId);
				intent.putExtra("yjfPaypassUrl", yjfPaypassUrl);
				intent.putExtra("mobile", mobile);
				startActivityForResult(intent, CommonData.CONFIRMATION_TRANSFER);
			}
		}
	}
	
}
